package com.coc.ofmylistener.event.spring;

import com.coc.ofmylistener.event.Event;
import com.coc.ofmylistener.event.EventHandler;
import org.springframework.beans.factory.BeanFactory;

import java.lang.reflect.Method;

public class SpringEventHandler implements EventHandler {

    private final Class<?> eventType;   // 参数的类类型
    private final String beanName;
    private final Method method;
    private final BeanFactory beanFactory;
    private final boolean asynchronous;

    public SpringEventHandler(Class<?> eventType, String beanName, Method method, BeanFactory beanFactory, boolean asynchronous) {
        this.eventType = eventType;
        this.beanName = beanName;
        this.method = method;
        this.beanFactory = beanFactory;
        this.asynchronous = asynchronous;
    }

    @Override
    public boolean asynchronous() {
        return asynchronous;
    }

    /**
     * 参数类类型与event 类类型，是否为起子类，实现类
     * class1.isAssignableFrom(class2)
     * class2是不是class1的子类或者子接口
     * @param event
     * @return
     */
    @Override
    public boolean canHandler(Event event) {
        return eventType.isAssignableFrom(event.getClass());
    }

    @Override
    public void handler(Event event) {
        Object bean = beanFactory.getBean(beanName);
       try{
           method.invoke(bean,event);
       }catch (Exception e ) {
            throw new RuntimeException(e);
       }
    }

}
